<template>
  <div class="ai-chat-container">
    <div class="knowledge-select-bar">
      <el-select v-model="selectedKnowledgeId" placeholder="请选择知识库" style="width: 220px">
        <el-option
          v-for="kb in knowledgeList"
          :key="kb.id"
          :label="kb.name"
          :value="kb.id"
        />
      </el-select>
      <el-button type="primary" @click="buildVectorDB" :disabled="!selectedKnowledgeId" style="margin-left: 12px;">构建向量数据库</el-button>
    </div>
    <div v-if="topChunks.length">
      <el-button size="small" @click="showChunks = !showChunks" style="margin-bottom: 8px;">
        {{ showChunks ? '收起相关文档片段' : '展开相关文档片段' }}
      </el-button>
    </div>
    <div v-if="topChunks.length && showChunks" class="rag-chunks">
      <div class="rag-chunk-title">相关文档片段：</div>
      <div v-for="(chunk, idx) in topChunks" :key="idx" class="rag-chunk-item">
        <div class="rag-doc-name">文档：{{ chunk.docName }}</div>
        <div class="rag-chunk-content">
          片段：
          <span v-if="!expandedChunks[idx]">
            {{ chunk.chunkContent.length > 80 ? chunk.chunkContent.slice(0, 80) + '...' : chunk.chunkContent }}
            <el-link v-if="chunk.chunkContent.length > 80" type="primary" @click="toggleChunk(idx)">展开</el-link>
          </span>
          <span v-else>
            {{ chunk.chunkContent }}
            <el-link type="primary" @click="toggleChunk(idx)">收起</el-link>
          </span>
        </div>
        <div class="rag-chunk-score">得分：{{ chunk.score }}</div>
      </div>
    </div>
    <div class="chat-history">
      <div v-for="(msg, idx) in messages" :key="idx" :class="msg.role">
        <span class="role">{{ msg.role === 'user' ? '我' : 'AI' }}：</span>
        <span class="content" v-html="renderMarkdown(msg.content)"></span>
      </div>
    </div>
    <div class="chat-input">
      <el-input
        v-model="input"
        type="textarea"
        :autosize="{ minRows: 2, maxRows: 6 }"
        placeholder="请输入你的问题..."
        @keyup.enter.native="sendMessage"
        clearable
      />
      <el-button type="primary" @click="sendMessage">发送</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { useKnowledgeStore } from '@/stores/knowledge'
import { storeToRefs } from 'pinia'
import { buildVectorDBAPI, ragAnswerAPI } from '@/api/knowledge'
import { getUserId } from '@/utils/auth'
import { marked } from 'marked'

interface Message {
  role: 'user' | 'ai';
  content: string;
}

const input = ref('')
const messages = ref<Message[]>([])
const selectedKnowledgeId = ref<string | null>(null)
const topChunks = ref<{docName: string, chunkContent: string, score: number}[]>([])
const aiFinalAnswer = ref('')
const expandedChunks = ref<Record<number, boolean>>({})
const showChunks = ref(true)

const knowledgeStore = useKnowledgeStore()
const { knowledgeList } = storeToRefs(knowledgeStore)

onMounted(() => {
  if (!knowledgeList.value.length) {
    knowledgeStore.fetchKnowledgeList()
  }
})

function renderMarkdown(content: string) {
  return marked.parse(content || '')
}

async function sendMessage() {
  if (!input.value.trim()) return
  messages.value.push({ role: 'user', content: input.value })
  const question = input.value
  input.value = ''
  messages.value.push({ role: 'ai', content: 'AI正在思考...' })
  topChunks.value = []
  aiFinalAnswer.value = ''
  expandedChunks.value = {}
  try {
    // RAG问答API
    const userId = getUserId()
    if (!userId || !selectedKnowledgeId.value) {
      messages.value[messages.value.length - 1].content = '请先选择知识库并登录';
      return
    }
    const res = await ragAnswerAPI({
      userId,
      kbId: selectedKnowledgeId.value,
      prompt: question,
      top_k: 3
    })
    // 渲染得分靠前的chunk
    if (res && res.chunks && Array.isArray(res.chunks)) {
      topChunks.value = res.chunks.map((c: any) => ({
        docName: c.docName,
        chunkContent: c.chunkContent,
        score: c.score
      }))
    }
    // 渲染大模型最终回答（llm_answer字段）
    aiFinalAnswer.value = res.llm_answer || res.answer || '（未返回大模型最终回答）'
    messages.value[messages.value.length - 1].content = aiFinalAnswer.value
    await nextTick()
    scrollToBottom()
  } catch (e) {
    messages.value[messages.value.length - 1].content = 'AI服务异常，请稍后再试。'
    ElMessage.error('AI服务异常')
  }
}

async function buildVectorDB() {
  if (!selectedKnowledgeId.value) return
  const userId = getUserId()
  if (!userId) {
    ElMessage.error('请先登录')
    return
  }
  try {
    const res = await buildVectorDBAPI(userId, selectedKnowledgeId.value)
    if (res && res.code === 200) {
      ElMessage.success('构建向量数据库成功！')
    } else {
      ElMessage.error('构建失败：' + (res?.message || '未知错误'))
    }
  } catch (e) {
    ElMessage.error('构建向量数据库请求异常')
  }
}

function toggleChunk(idx: number) {
  expandedChunks.value[idx] = !expandedChunks.value[idx]
}

function scrollToBottom() {
  const container = document.querySelector('.chat-history')
  if (container) {
    container.scrollTop = container.scrollHeight
  }
}
</script>

<style scoped>
.ai-chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 24px;
  background: #fff;
  box-sizing: border-box;
}
.knowledge-select-bar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  gap: 8px;
}
.chat-history {
  flex: 1;
  overflow-y: auto;
  margin-bottom: 16px;
  padding-bottom: 8px;
}
.user {
  text-align: right;
  margin: 8px 0;
}
.ai {
  text-align: left;
  margin: 8px 0;
}
.user .content {
  display: inline-block;
  background: #e6f7ff;
  color: #222;
  border-radius: 12px 12px 0 12px;
  padding: 4px 10px;
  max-width: 60vw;
  word-break: break-all;
}
.ai .content {
  display: inline-block;
  background: #f4f4f4;
  color: #222;
  border-radius: 12px 12px 12px 0;
  padding: 4px 10px;
  max-width: 60vw;
  word-break: break-all;
}
.role {
  font-weight: bold;
  margin-right: 4px;
}
.chat-input {
  display: flex;
  gap: 8px;
  padding: 12px 0 0 0;
  background: #fff;
  position: sticky;
  bottom: 0;
  z-index: 2;
}
@media (max-width: 600px) {
  .ai-chat-container {
    padding: 8px;
  }
  .chat-input {
    flex-direction: column;
    gap: 4px;
  }
  .user .content, .ai .content {
    max-width: 90vw;
  }
}
.rag-chunks {
  background: #f9fafb;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px 16px;
  margin-bottom: 16px;
}
.rag-chunk-title {
  font-weight: bold;
  margin-bottom: 8px;
}
.rag-chunk-item {
  margin-bottom: 8px;
  padding-bottom: 8px;
  border-bottom: 1px dashed #e4e7ed;
}
.rag-doc-name {
  color: #409eff;
  font-weight: bold;
}
.rag-chunk-content {
  margin: 4px 0;
}
.rag-chunk-score {
  color: #aaa;
  font-size: 12px;
}
</style> 